﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using NRCP.App_Logic.Dummy;
using System.Web.Script.Services;
using NRCP.BusinessEntities;
using NRCP.BusinessLogicLayer;
using NRCP.Helpers;
using System.Globalization;
using System.Text;

namespace NRCP.App_Service
{
    /// <summary>
    /// Summary description for SiteDataUtility
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class SiteDataUtility : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempValueObject> LoadPlanMonths(int planId)
        {
            List<TempValueObject> dicDivistion = new List<TempValueObject>();
            NationalPlanDetailsMonthlyBLL bll = new NationalPlanDetailsMonthlyBLL();
            List<NationalPlanDetailsMonthly> monthlies = bll.GetNationalPlanDetailsMonthliesByNationalPlanId(planId);
            var orderGroups =
          from p in monthlies
          group p by p.Month into g
          select new { Category = g.Key, Products = g };
            foreach (var g in orderGroups)
            {
                TempValueObject obj = new TempValueObject();
                obj.Key = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(g.Category); ;
                obj.Value = g.Category.ToString();
                dicDivistion.Add(obj);
            }

            return dicDivistion;
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempValueObject> LoadPlanRegion(int planId)
        {
            List<TempValueObject> dicDivistion = new List<TempValueObject>();
            NationalPlanDivisionBLL bll = new NationalPlanDivisionBLL();
            List<NationalPlanDivision> divisions = bll.GetNationalPlanDivisionsByNationalPlanId(planId);
            foreach (NationalPlanDivision division in divisions)
            {

                TempValueObject obj = new TempValueObject();
                obj.Key = division.Division.Name;
                obj.Value = division.Id.ToString();
                dicDivistion.Add(obj);
            }

            return dicDivistion;
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempValueObject> LoadDivision(int planId)
        {
            List<TempValueObject> dicDivistion = new List<TempValueObject>();
            NationalPlanDivisionBLL bll = new NationalPlanDivisionBLL();
            List<NationalPlanDivision> divisions = bll.GetNationalPlanDivisionsByNationalPlanId(planId);
            foreach (NationalPlanDivision division in divisions)
            {

                TempValueObject obj = new TempValueObject();
                obj.Key = division.Division.Name;
                obj.Value = division.Division.Id.ToString();
                dicDivistion.Add(obj);
            }

            return dicDivistion;
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempValueObject> LoadDistrict(int divisionId)
        {
            DistrictBLL bll = new DistrictBLL();
            List<District> dsitrics = bll.GetDistricts(obj => obj.DivisionId == divisionId);
            return dsitrics.ToList().ConvertAll(x => new TempValueObject { Key = x.Name, Value = x.Id.ToString() });
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempValueObject> LoadDistrictByPlanDivision(int nationalPlanId, int divisionId)
        {
            NationalPlanDivisionBLL divisionbll = new NationalPlanDivisionBLL();
            NationalPlanDivision planDivision = divisionbll.GetNationalPlanDivision(obj => obj.NationalPlanId == nationalPlanId && obj.Id == divisionId);

            DistrictBLL bll = new DistrictBLL();
            List<District> dsitrics = bll.GetDistricts(obj => obj.DivisionId == planDivision.DivisionId);
            return dsitrics.ToList().ConvertAll(x => new TempValueObject { Key = x.Name, Value = x.Id.ToString() });
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempValueObject> LoadUpazila(int districtId)
        {
            SubDistrictBLL bll = new SubDistrictBLL();
            List<SubDistrict> subDistrics = bll.GetSubDistricts(obj => obj.DistrictId == districtId);
            return subDistrics.ToList().ConvertAll(x => new TempValueObject { Key = x.Name, Value = x.Id.ToString() });
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempMonthScheduler> SaveMonthlyPlan(int nationalPlanId, int divId, int fishId, int chemicalGroupId, string chemicalGroup, int upazilaId, string upazilaName, int monthId, string monthName, int count)
        {
            List<TempMonthScheduler> tmpList = SessionManager.TEMP_NATIONALPLAN_MONTHLY;
            NationalPlanDetailsYearlyBLL nationalPlanDetailsYearlyBLL = new NationalPlanDetailsYearlyBLL();
            NationalPlanDetailsYearly yearlyPlan = nationalPlanDetailsYearlyBLL.GetNationalPlanDetailsYearly(obj => obj.NationalPlanId == nationalPlanId && obj.FishId == fishId && obj.DivisionId == divId && obj.ChemicalGroupId == chemicalGroupId);
            if (yearlyPlan != null)
            {
                List<NationalPlanDetailsMonthly> list;


                NationalPlanDetailsMonthly nationalPlanDetailsMonthly = new NationalPlanDetailsMonthly();
                nationalPlanDetailsMonthly.Count = count;
                nationalPlanDetailsMonthly.Month = monthId;
                nationalPlanDetailsMonthly.SubDistrictId = upazilaId;
                nationalPlanDetailsMonthly.NationalPlanDetailsYearlyId = yearlyPlan.Id;

                TempMonthScheduler scheduler = new TempMonthScheduler();
                scheduler.Count = nationalPlanDetailsMonthly.Count;
                scheduler.Month = monthName;
                scheduler.Group = chemicalGroup;
                scheduler.Division = upazilaName;
                tmpList.Add(scheduler);
                SessionManager.TEMP_NATIONALPLAN_MONTHLY = tmpList;

                if (SessionManager.NATIONALPLAN_MONTHLY != null)
                {
                    list = SessionManager.NATIONALPLAN_MONTHLY;
                }
                else
                {
                    list = new List<NationalPlanDetailsMonthly>();
                }
                list.Add(nationalPlanDetailsMonthly);
                SessionManager.NATIONALPLAN_MONTHLY = list;
                List<TempValueObject> tmpVal = SessionManager.TEMP_VAL_CONTAINER;

                foreach (TempValueObject tmp in tmpVal)
                {
                    if (tmp.Key.ToLower().Equals(scheduler.Division.ToLower()))
                    {
                        tmp.Value = (Convert.ToInt32(tmp.Value) - scheduler.Count).ToString();
                    }
                }
                SessionManager.TEMP_VAL_CONTAINER = tmpVal;

            }


            return tmpList;
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<TempValueObject> LoadPlanSummaryByDivisionAndFish(int nationalPlanId, int divisionId, int fishId)
        {
            NationalPlanDetailsYearlyBLL nationalPlanDetailsYearlyBLL = new NationalPlanDetailsYearlyBLL();
            List<NationalPlanDetailsYearly> nationalPlanDetailsYearlys = nationalPlanDetailsYearlyBLL.GetNationalPlanDetailsYearlys(obj => obj.NationalPlanId == nationalPlanId && obj.FishId == fishId && obj.DivisionId == divisionId);
            List<TempValueObject> tmpVal = nationalPlanDetailsYearlys.ToList().ConvertAll(x => new TempValueObject { Key = x.NationalPlanChemicalGroup.ChemicalGroup.Name, Value = x.Count.ToString() });
            return tmpVal;
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public bool SaveMonthlyPlanAll(int nationalPlanId, int divId, int fishId)
        {
            List<NationalPlanDetailsMonthly> list = SessionManager.NATIONALPLAN_MONTHLY;
            if (list.Count > 0)
            {
                List<Int32> idList = new List<int>();
                int monthPlanId;
                int yearid = 0;
                NationalPlanDetailsMonthlyBLL bll = new NationalPlanDetailsMonthlyBLL();
                NationalPlanDetailsYearlyBLL nationalPlanDetailsYearlyBLL = new NationalPlanDetailsYearlyBLL();
                try
                {
                    foreach (NationalPlanDetailsMonthly plan in list)
                    {
                        yearid = plan.NationalPlanDetailsYearlyId;
                        monthPlanId = bll.CreateNewNationalPlanDetailsMonthly(plan);
                        if (monthPlanId > 0)
                        {
                            idList.Add(monthPlanId);
                        }
                        else
                            throw new Exception("cant create monthly plan"); ;
                    }

                    if (idList.Count > 0)
                    {
                        foreach (NationalPlanDetailsMonthly plan in list)
                        {
                            NationalPlanDetailsYearly yearlyPlan = nationalPlanDetailsYearlyBLL.GetNationalPlanDetailsYearlyById(plan.NationalPlanDetailsYearlyId);
                            yearlyPlan.Status = PlanStatus.Complete.ToString();
                            nationalPlanDetailsYearlyBLL.UpdateNationalPlanDetailsYearly(yearlyPlan);
                        }
                    }
                    return true;
                }
                catch
                {
                    bll.DeleteNationalPlanDetailsMonthlies(idList);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        #region Charts

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public List<String> ReportGetOpenPlan()
        {
            List<String> planCompa = new List<String>();
            NationalPlanBLL planbll = new NationalPlanBLL();
            List<NationalPlan_GetSummaryStat_Result> result = planbll.GetPlanComparisonByCount();
            List<int?> planyears = (from lst in result select lst.PlanYear).Distinct().ToList<int?>();
            StringBuilder category = new StringBuilder();
            category.Append("[");
            foreach (int planyear in planyears)
            {
                category.Append("'" + planyear + "',");
            }
            string planCategory = category.ToString().Substring(0, category.Length - 1);
            planCategory += "]";
            planCompa.Add(planCategory);

            StringBuilder compData = new StringBuilder();
            List<String> planFishes = (from lst in result select lst.Name).Distinct().ToList<String>();
            compData.Append("[");
            foreach (String fish in planFishes)
            {
                compData.Append("{");
                compData.Append(@"name: '" + fish + "',");
                List<NationalPlan_GetSummaryStat_Result> totalDistByFishes = result.Where(obj => obj.Name == fish).ToList();
                compData.Append("data: [");
                foreach (NationalPlan_GetSummaryStat_Result totalDistByFishe in totalDistByFishes)
                {
                    compData.Append(totalDistByFishe.TotalSample.ToString()+",");
                    
                }
                compData.Remove(compData.Length - 1, 1);
                compData.Append("]");
                compData.Append("},");
                
            }
            compData.Remove(compData.Length - 1, 1);
            compData.Append("]");

            string plancompData = compData.ToString();
            planCompa.Add(plancompData);

            return planCompa;
        }

        #endregion
    }
}
